var hostConfig = window.hostConfig || {
	APIHost: 'https://api.bimface.com',
	resourceHost: 'https://m.bimface.com',
	staticHost: 'https://static.bimface.com',
	dataEnvType: 'BIMFACE'
};
void 0 === Object.assign &&
	(Object.assign = function (e) {
		if (null == e) throw new TypeError('Cannot convert undefined or null to object');
		for (var t = Object(e), o = 1; o < arguments.length; o++) {
			var a = arguments[o];
			if (null != a) for (var n in a) Object.prototype.hasOwnProperty.call(a, n) && (t[n] = a[n]);
		}
		return t;
	});
let BimfaceConfigrationOption = Object.freeze({ Release: 'Release', Debug: 'Debug' }),
	BimfaceViewTypeOption = Object.freeze({ Normal: 'Normal', DrawingView: 'drawingView' }),
	BimfaceEnvOption = Object.freeze({ BIMFACE: 'BIMFACE', Local: 'Local' }),
	BimfaceLanguageOption = Object.freeze({ zh_CN: 'zh_CN', en_GB: 'en_GB', sv_SE: 'sv_SE' }),
	BimfaceVisualStyle = Object.freeze({ Normal: 'Normal', Bake: 'Bake' });
var BimfaceSDKLoaderConfig$1 = function () {
	if (window.hostConfig) for (let e in window.hostConfig) hostConfig[e] = window.hostConfig[e];
	return {
		staticHost: `${hostConfig.staticHost}/api`,
		APIHost: hostConfig.APIHost,
		language: 'zh_CN',
		viewToken: null,
		configuration: BimfaceConfigrationOption.Release,
		dataEnvType: hostConfig.dataEnvType || 'BIMFACE',
		viewType: BimfaceViewTypeOption.Normal,
		visualStyle: BimfaceVisualStyle.Bake,
		version: ''
	};
};
(window.BimfaceSDKLoaderConfig = BimfaceSDKLoaderConfig$1),
	(window.BimfaceEnvOption = BimfaceEnvOption),
	(window.BimfaceLanguageOption = BimfaceLanguageOption),
	(window.BimfaceConfigrationOption = BimfaceConfigrationOption),
	(window.BimfaceViewTypeOption = BimfaceViewTypeOption);
var version = '2021-4-2-18-18';
let transfromPath = function (e) {
	let t = e.split('/');
	return t.pop(), t.join('/') + '/';
};
var getConfig = function (e) {
		let t = Object.assign({}, e),
			o = '/Glodon';
		return (
			e.path
				? ((t.dataEnvType = BimfaceEnvOption.Local),
					(t.url = t.path),
					(t.staticHost = t.sdkPath || transfromPath(t.path)),
					(t.resourcePath = transfromPath(t.path)),
					(t.path = transfromPath(t.path)),
					(o = t.sdkPath ? '' : '/jssdk'))
				: e.resourcePath
					? ((t.dataEnvType = BimfaceEnvOption.Local),
						(t.url = t.resourcePath),
						(t.resourcePath = transfromPath(t.resourcePath)))
					: (t.sdkPath && ((o = ''), (t.staticHost = t.sdkPath)),
						(t.url = `${e.APIHost}/inside/databag?viewToken=${e.viewToken}`)),
			(t.staticHost += o),
			(e.build != BimfaceConfigrationOption.Debug &&
				t.configuration != BimfaceConfigrationOption.Release) ||
				(t.configuration = ''),
			(t.configuration = t.configuration ? `-${t.configuration.toLowerCase()}` : ''),
			t
		);
	},
	transformFullUrl = function (e, t) {
		for (var o = 0; o < t.length; o++) t[o] = e + t[o];
	},
	isDrawingView = function (e, t) {
		return 'drawingView' == e.renderType || t.viewType == BimfaceViewTypeOption.DrawingView;
	},
	getLoadModules = function (e) {
		var t = e.sdkVersion,
			o = e.options,
			a = o.configuration,
			n = [],
			r = [`/${t}/${o.language}.js`, `/${t}/Application${a}.js`];
		return (n = isDrawingView(e.metadata, e.options)
			? [...n, ...r, `/${t}/Drawing.css`, `/${t}/bimface.bufferfly.js`, `/${t}/Drawing${a}.js`]
			: [
					...n,
					...r,
					`/${t}/Bimface.css`,
					`/${t}/thirdparty.js`,
					`/${t}/lib/loaders/BimTilesLoader.js`,
					`/${t}/Bimface${a}.js`
				]);
	};
window.postProcessing = function (e) {
	var t = e.metadata,
		o = e.options,
		a = e.successCb,
		n = getLoadModules(e);
	transformFullUrl(o.staticHost, n),
		(t.databagId = `${t.databagId}`),
		o.path
			? ((t.path = o.path), (t.dataPath = './'))
			: o.resourcePath && (t.path = o.resourcePath.replace('viewToken', '')),
		(t.sdkPath = o.sdkPath),
		0 == n.length
			? a(t)
			: loadResource(n, function () {
					if (o.build === BimfaceConfigrationOption.Debug && o.dataPath) {
						let e = o.dataPath.split('/');
						a({ databagId: e.pop(), path: e.join('/') });
					}
					a(t);
				});
};
var loadResource = function (e, t, o) {
		var a = e.length,
			n = 0,
			r = function (i) {
				if (i && 'error' == i.message && i.element.indexOf('bimface.index') > -1) {
					n = 0;
					var s = o.options;
					s.build, BimfaceConfigrationOption.Release;
					var d = getLoadModules(o);
					return transformFullUrl(s.staticHost, d), void loadResource(d, t);
				}
				++n == a ? t() : createResource(e[n], r);
			};
		createResource(e[n], r);
	},
	loaded = [],
	createResource = function (e, t) {
		if (!(loaded.indexOf(e.split('/').pop()) > -1)) {
			var o,
				a = document.getElementsByTagName('head')[0];
			return (
				e.indexOf('.css') > -1
					? ((o = document.createElement('link')).setAttribute('href', e),
						o.setAttribute('rel', 'stylesheet'))
					: (o = document.createElement('script')).setAttribute('src', e),
				(o.url = e),
				a.appendChild(o),
				o.addEventListener('load', function () {
					loaded.push(this.url.split('/').pop()), t && t({ message: 'success' });
				}),
				o.addEventListener('error', function () {
					t && t({ element: e, message: 'error' });
				}),
				o
			);
		}
		t();
	};
window.loadResource = loadResource;
var ajax = function (e) {
	var t,
		o = Object.assign({ type: 'get', data: null, success: null, failure: null }, e);
	((t = window.XMLHttpRequest
		? new XMLHttpRequest()
		: new ActiveXObject('Microsoft.XMLHTTP')).onreadystatechange = function () {
		if (4 == t.readyState) {
			var e = t.status;
			(e >= 200 && e < 300) || 304 == e || (0 === e && 'file:' === window.location.protocol)
				? o.success && o.success(t.responseText, t.responseXML)
				: o.failure && o.failure(e);
		}
	}),
		t.open(o.type, o.url, o.async),
		t.send(o.data);
};
class IndexedDBHelper {
	constructor(e) {
		(this.indexedDB =
			window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.msIndexedDB),
			this.indexedDB || console.log('IndexedDB not supported'),
			(this._db = null),
			(this._opt = e);
	}
	open(e, t) {
		const o = e || this._opt.name,
			a = t || this._opt.version || 1,
			n = this.indexedDB.open(o, a);
		return new Promise((e, t) => {
			(n.onsuccess = (t) => {
				(this._db = n.result), e(this._db);
			}),
				(n.onupgradeneeded = (e) => {
					let t = (this._db = e.target.result);
					(this._opt.storeList || []).forEach(
						(e) => !t.objectStoreNames.contains(e) && t.createObjectStore(e)
					);
				}),
				(n.onerror = (e) => {
					t(e);
				});
		});
	}
	getDB() {
		return new Promise((e, t) => {
			this._db ? e(this._db) : this.open().then(e).catch(t);
		});
	}
	addObject(e, t, o) {
		return new Promise((a, n) => {
			this.getDB()
				.then((r) => {
					const i = r.transaction(e, 'readwrite');
					(i.objectStore(e).put(t, o).onsuccess = (e) => {
						a(e.target.result);
					}),
						(i.onerror = (e) => {
							n(e);
						});
				})
				.catch(n);
		});
	}
	getObject(e, t) {
		return new Promise((o, a) => {
			this.getDB()
				.then((n) => {
					const r = n.transaction(e, 'readonly');
					(r.objectStore(e).get(t).onsuccess = (e) => {
						let t = e.target.result;
						t ? o(t) : a(e);
					}),
						(r.onerror = (e) => {
							a(e);
						});
				})
				.catch(a);
		});
	}
	deleteObject(e, t) {
		return new Promise((o, a) => {
			this.getDB()
				.then((n) => {
					const r = n.transaction(e, 'readwrite');
					(r.objectStore(e).delete(t).onsuccess = (e) => {
						o(e.target.result);
					}),
						(r.onerror = (e) => {
							a(e);
						});
				})
				.catch(a);
		});
	}
	clearStore(e) {
		return new Promise((t, o) => {
			this.getDB()
				.then((a) => {
					const n = a.transaction(e, 'readwrite');
					(n.objectStore(e).clear().onsuccess = (e) => {
						t(e.target.result);
					}),
						(n.onerror = (e) => {
							o(e);
						});
				})
				.catch(o);
		});
	}
	deleteDB(e) {
		return new Promise((t) => {
			this.indexedDB.deleteDatabase(e), t();
		});
	}
	getAllKeys(e) {
		return new Promise((t, o) => {
			this.getDB()
				.then((a) => {
					const n = a.transaction(e, 'readonly');
					(n.objectStore(e).getAllKeys().onsuccess = (e) => t(e.target.result)), (n.onerror = o);
				})
				.catch(o);
		});
	}
	getAll(e) {
		return new Promise((t, o) => {
			this.getDB()
				.then((a) => {
					const n = a.transaction(e, 'readonly');
					(n.objectStore(e).getAll().onsuccess = (e) => t(e.target.result)), (n.onerror = o);
				})
				.catch(o);
		});
	}
}
class LoaderStorageManager extends IndexedDBHelper {
	constructor() {
		super({ name: 'Bf_Loader', version: 1, storeList: ['d', 't'] });
	}
	getDatabagInfo(e, t) {
		return new Promise((o, a) => {
			t
				? this.getObject('d', e)
						.then((e) =>
							this.addTemp(e, t)
								.then(() => o(e))
								.catch(a)
						)
						.catch(a)
				: this.getObject('d', e).then(o).catch(a);
		});
	}
	addDatabagInfo(e, t) {
		return new Promise((o, a) => {
			const n = e.modelId,
				r = () =>
					Promise.all([this.addObject('d', e, n), this.addTemp(e, t)])
						.then(o)
						.catch(a);
			this.getDatabagInfo(n)
				.then((t) => {
					t.databagId !== e.databagId && this.deleteDB(`Bf_${data.databagId}`), r();
				})
				.catch(() => {
					r();
				});
		});
	}
	deleteDatabagInfo(e) {
		return new Promise((t, o) => {
			this.deleteObject('d', e).then(t).catch(o);
		});
	}
	addTemp(e, t) {
		return new Promise((o, a) => {
			this.clearStore('t')
				.then(() => {
					this.addObject('t', e, t).then(o).catch(a);
				})
				.catch(a);
		});
	}
	getTemp(e) {
		return new Promise((t, o) => {
			this.getObject('t', e).then(t).catch(o);
		});
	}
	deleteStorageByModelId(e) {
		return new Promise((t) => {
			this.getDatabagInfo(e)
				.then((o) => {
					let a = 'gisView' === o.renderType ? `Bg_${o.modelId}` : `Bf_${o.databagId}`;
					Promise.allSettled([this.deleteDB(a), this.deleteDatabagInfo(e)]).then(t);
				})
				.catch(t);
		});
	}
	getStoredModelIds() {
		return this.getAllKeys('d');
	}
	getStoredModelInfo() {
		return new Promise((e, t) => {
			this.getAll('d')
				.then((t) => {
					let o = t.map((e) => {
						let { modelId: t, name: o, renderType: a } = e;
						return { modelId: t, name: o, type: a };
					});
					e(o);
				})
				.catch(t);
		});
	}
}
var getMetadata = function (e, t, o) {
		const a = (a) => {
			if (e.enableStorage && e.modelId) {
				new LoaderStorageManager()
					.getDatabagInfo(e.modelId, e.viewToken)
					.then((e) => o && o(e))
					.catch(() => {
						console.error('[BIMFACE ERROR]: failed get model info from storage'), t && t(a);
					});
			} else t && t(a);
		};
		e.viewToken || 'Local' === e.dataEnvType
			? ajax({
					url: e.url,
					async: !0,
					success: function (t) {
						var n = JSON.parse(t);
						if ('Local' !== e.dataEnvType && 'success' !== n.code)
							return n.message && console.error(`[BIMFACE ERROR]: ${n.message}`), void a(t);
						if (((n = n.data || n), e.enableStorage)) {
							new LoaderStorageManager()
								.addDatabagInfo(n, e.viewToken)
								.then(() => o && o(n))
								.catch(() => o && o(n));
						} else o && o(n);
					},
					failure: a
				})
			: a();
	},
	getVersion = function (e, t) {
		let o,
			a = t.version;
		e.renderVersion;
		if (/\d+?\.\d+?\.\d+/.test(a) && a.split('.')[0] >= 3) {
			const [e, t, o] = a.split('.');
			'6' === t && Number(o) < 143 && (a = `Bimface@${a}`);
		} else if ('Debug' == t.build) (a = 'Bimface'), (o = 'Application');
		else if (t.sdkPath) a = o = 'bimface';
		else if (t.viewType == BimfaceViewTypeOption.DrawingView && 'drawingView' != e.renderType) {
			var n = e.subRenders;
			if (n && 0 != n.length)
				for (var r = 0; r < n.length; r++)
					n[r].renderType == BimfaceViewTypeOption.DrawingView &&
						((a = n[r].jsSDKVersion), (o = n[r].jsSDKVersion));
		} else (a = e.jsSDKVersion), (o = e.jsSDKVersion);
		return { ui: o, sdk: a };
	},
	loaderPreProcessing = function (e, t, o) {
		getMetadata(e, o, function (o) {
			var a = getVersion(o, e);
			window.BimfaceLoaderConfig.fullStaticHost =
				'Local' == BimfaceLoaderConfig.dataEnvType
					? e.staticHost + '/bimface'
					: e.staticHost + '/' + a.sdk;
			var n = { metadata: o, options: e, successCb: t, sdkVersion: a.sdk, uiVersion: a.ui },
				r = window.BimfaceLoaderConfig.fullStaticHost + '/bimface.index.js';
			loadResource(
				[r],
				function () {
					postProcessing(n);
				},
				n
			);
		});
	},
	formatData = function (e, t) {
		var o = 'bimView' == e.renderType ? '3DView' : e.renderType,
			a =
				(e.subRenders,
				{
					dataEnvType: t.dataEnvType,
					viewToken: t.viewToken,
					staticHost: t.staticHost,
					APIHost: t.APIHost,
					viewType: o
				});
		return Object.assign(a, e);
	},
	Storage = {
		getStorage() {
			return (this.storage = this.storage || new LoaderStorageManager()), this.storage;
		},
		deleteStorageByModelId(e) {
			return this.getStorage().deleteStorageByModelId(e);
		},
		getStoredModelIds() {
			return this.getStorage().getStoredModelIds();
		},
		getStoredModelInfo() {
			return this.getStorage().getStoredModelInfo();
		},
		store(e) {
			let {
				url: t,
				viewToken: o,
				storeMaterialOverride: a,
				successCallback: n,
				progressCallback: r,
				errorCallback: i,
				conditions: s,
				storeByQueue: d
			} = e;
			const c = d && d.enable,
				l = c && (d.delay || 2e3);
			if (!o) return;
			(t = t || []),
				(n = n || function () {}),
				(r = r || function () {}),
				(i = i || function () {});
			const f = new BimfaceSDKLoaderConfig();
			(f.enableStorage = !0),
				(f.viewToken = o),
				BimfaceSDKLoader.load(f)
					.then((e) => {
						if ('3DView' == e.viewType) {
							const d = document.createElement('div'),
								f = new Glodon.Bimface.Viewer.Viewer3DConfig();
							(f.domElement = d), (f.enableStorage = !0);
							const u = new Glodon.Bimface.Viewer.Viewer3D(f),
								g = new Promise((t) => {
									u.addModel(e),
										c ||
											u.addEventListener(Glodon.Bimface.Viewer.Viewer3DEvent.ViewLoading, (e) =>
												r(e.progress)
											);
									const n = () => {
										requestAnimationFrame(() => {
											u.destroy(), t();
										});
									};
									let i = !1;
									u.addEventListener(Glodon.Bimface.Viewer.Viewer3DEvent.ViewAdded, () => {
										if (i) return;
										const e = () => {
											i = !0;
											const e = u.getDefaultModel(),
												t = e.getCloudViewer().getModelManager().getModel(e.modelId),
												a = [...t._handler.layerProvider.getAllLayerIdxData().layerKeys],
												s = [...t._handler.layerProvider.getLayerKeyAttributes()];
											let d = 0;
											const c = {},
												f = () => {
													if ((r(Math.floor((100 * (d + 1)) / a.length)), d === a.length))
														return void n();
													a[d].split('-').forEach((e, t) => (c[s[t]] = e));
													const e = u.getDefaultModel();
													e && e.destroy();
													const t = isNaN(l) ? 2e3 : Number(l);
													setTimeout(() => {
														u.addView(o);
													}, t),
														d++;
												};
											u.addEventListener(Glodon.Bimface.Viewer.Viewer3DEvent.ModelAdded, () => {
												u.showExclusiveComponentsByObjectData([c], null, f);
											}),
												f();
										};
										a
											? u.loadMaterialOverrideSet(u.getModel().modelId, o, function () {
													s
														? u.showExclusiveComponentsByObjectData(s, null, n)
														: c
															? e()
															: (u.showAllComponents(),
																u.addEventListener(
																	Glodon.Bimface.Viewer.Viewer3DEvent.DemandLoaded,
																	n
																));
												})
											: s
												? u.showExclusiveComponentsByObjectData(s, null, n)
												: c
													? e()
													: n();
									});
								});
							Promise.all([g, u._storeData(t)])
								.then(n)
								.catch(i);
						}
					})
					.catch();
		}
	},
	BimfaceSDKLoader$1 = {
		Version: version,
		load: function (e, t, o) {
			(window.BimfaceLoaderConfig = e),
				null == e.build && (e.build = BimfaceConfigrationOption.Release);
			var a = getConfig(e);
			if (!t && !o)
				return new Promise((t, o) => {
					loaderPreProcessing(
						a,
						function (o) {
							t(formatData(o, e));
						},
						o
					);
				});
			loaderPreProcessing(
				a,
				function (o) {
					t && t(formatData(o, e));
				},
				function (e) {
					o && o();
				}
			);
		},
		Storage: Storage
	};
(window.BimfaceSDKLoader = BimfaceSDKLoader$1), window.Glodon || (window.Glodon = {});
const Glodon$1 = window.Glodon,
	BimfaceSDKLoader$2 = window.BimfaceSDKLoader;
export {
	BimfaceSDKLoader$2 as BimfaceSDKLoader,
	BimfaceSDKLoaderConfig$1 as BimfaceSDKLoaderConfig,
	Glodon$1 as Glodon,
	BimfaceEnvOption,
	BimfaceViewTypeOption,
	BimfaceLanguageOption,
	BimfaceVisualStyle
};
